<?php
/**
 * Created by PhpStorm.
 * User: Ysll <754060604@qq.com>
 * Date: 2017/9/7
 * Time: 11:51
 */
$db = require_once 'DatabaseService.php';
require 'UserService.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    return;
}

$data = $_POST;

$access = isset($data['access']) ? $data['access'] : null;
$password = isset($data['password']) ? $data['password'] : null;
$password_confirmed = isset($data['password_confirmed']) ? $data['password_confirmed'] : null;
$code = isset($data['code']) ? $data['code'] : '';

if ($access == null || $password == null) {
    $_SESSION['error_code'] = 1000;
    $_SESSION['error_data'] = '参数错误';
    return;
}

if ( 7 > mb_strlen($access) && mb_strlen($access) > 32) {
    $_SESSION['error_code'] = 10001;
    $_SESSION['error_data'] = '账户名必须在8 - 32 之间';
    return;
}

if ( 7 > mb_strlen($password) && mb_strlen($password) > 32) {
    $_SESSION['error_code'] = 10001;
    $_SESSION['error_data'] = '密码必须在8 - 32 之间';
    return;
}

if ($password !== $password_confirmed) {
    $_SESSION['error_code'] = 2000;
    $_SESSION['error_data'] = '两次输入的密码不匹配';
    return;
}
if (strtoupper($code) !== strtoupper($_SESSION['code'])) {
    $_SESSION['error_code'] = 2001;
    $_SESSION['error_data'] = '验证码不正确';
    return;
}

$_SESSION['error_code'] = 0;
if (!checkUser($access)) {
    saveUsers($db, $access, $password);
} else {
    $_SESSION['error_code'] = 2002;
    $_SESSION['error_data'] = '用户已存在';
}